import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        todos: JSON.parse(localStorage.getItem("vuex") || "[]"), //获取本地存储的vuex状态显示在todos中，如果本地没有就给个空数组，让新的东西存进来
        activeTab: "all", //给了一个状态位，默认显示的状态是所有
    },
    getters: {
        // 状态位
        activeTab: function(state) {
            return state.activeTab;
        },
        // 过滤todos,根据状态位显示隐藏
        filterTodos: function(state) {
            console.log(state.todos);
            if (state.activeTab === "all") {
                return state.todos;
            } else if (state.activeTab === "active") {
                return state.todos.filter((v) => {
                    //filter()方法是遍历筛选过滤出符合条件的元素并返回这个数组
                    // v.status => false   status为false显示active,为true显示completed
                    return !v.status;
                });
            } else if (state.activeTab === "completed") {
                return state.todos.filter((v) => {
                    // v.status => true
                    return v.status;
                });

            }
        },
        // 剩下项目,就是未完成的，就是active,所以在状态位是false时返回true 
        remaining: function(state) {
            let remainingTodos = state.todos.filter((v) => {
                // return !v.status // false => 返回
                if (!v.status) {
                    return true;
                }
            })
            return remainingTodos.length;
        },
        //全选
        allChecked: function(state) {
            // 先定义都被选中就是true
            let checked = true;
            // 只要todo 里面有一个未被选中（status false）那就不是全选，就=> allChecked = false
            state.todos.map((v) => {
                if (!v.status) { checked = false };
            })
        },
    },
    mutations: {
        // 添加todos
        addTodo: function(state, { payload }) {
            state.todos.push(payload)
        },
        //删除todo
        deletTodo: function(state, { payload }) {
            state.todos.splice(payload.index, 1)
        },
        // 更改状态位
        changeActiveTab: function(state, { payload }) {
            state.activeTab = payload.activeTab
        },
        // 清除已完成按钮，就是显示的都是active的就行
        handleClearCompleted: function(state) {
            // 筛选出未完成 => todos
            let activeTodos = state.todos.filter((v) => {
                // v.status => false
                return !v.status; // false => !false => true
            });
            state.todos = activeTodos
        },

        // 全选逻辑
        allCheck: function(state) {
            state.todos.map((v) => {
                v.status = true;
            })
            console.log(state.todos);
        },
    },
    actions: {},
    modules: {}
})